package com.ht.aems.fesservice.util;

import com.ht.aems.communicate.*;

import java.io.IOException;
import java.net.Socket;

/**
 * Tcp server class
 * <p> tcp socket connection server class for Formula company implementation <br>
 *
 * @author Dong Shufeng
 * @version 1.0
 * @Date: 2006-3-25
 */
public class FCTcpServer extends TcpServer {

    public FCTcpServer(int port, int mode) {
        super(port, mode);
    }

    public ITransmitPort accept() {
        try {
            Socket s = serverSocket.accept();
            System.out.println("client has been connected: " + s.getInetAddress().getHostAddress());
            String key;
            if (mode == ONE_CLIENT_ONLY_MODE)
                key = ONE_CLIENT_ONLY_KEY;
            else
                key = s.getInetAddress().getHostAddress();
            if (clients.containsKey(key)) {
                clients.get(key).stopAbnormally();
            }
            if (mode == ONE_CLIENT_ONLY_MODE) {
                ITransmitPort port = new TcpTransmitPort(s);
                clients.put(key, port);
                port.addPortErrorListener(this);
                return port;
            }
            for (String ip : FCRegisterServer.getInstance().getDeviceIpMap().values()) {
                if (s.getInetAddress().getHostAddress().equals(ip)) {
                    ITransmitPort port = new TcpTransmitPort(s);
                    clients.put(key, port);
                    port.addPortErrorListener(this);
                    return port;
                }
            }
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public ITransmitPort getTransPort(IPortInfo portInfo) {
        if (portInfo instanceof TcpPortInfo) {
            if (((TcpPortInfo) portInfo).getServerPort() == this.getServerPort())
                return clients.get(((TcpPortInfo) portInfo).getRemoteIp());
        }
        return null;
    }

    public ITransmitPort removePort(IPortInfo portInfo) {
        if (!(portInfo instanceof TcpPortInfo))
            return null;
        if (((TcpPortInfo) portInfo).getServerPort() != this.getServerPort())
            return null;
        return clients.remove(((TcpPortInfo) portInfo).getRemoteIp());
    }

    public boolean containsPort(IPortInfo portInfo) {
        return portInfo instanceof TcpPortInfo && clients.containsKey(((TcpPortInfo) portInfo).getRemoteIp());
    }
}